# -*- coding: UTF-8 -*-
import time
import os
from ftplib import FTP

logchan = {
    "#beeseek": False,
    "#rendon":  False,
    "#beeseek.org": False,
}    

chalogdirname = "chatlog"
ftphost = "jibbolo.altervista.org"
siteurl = "http://jibbolo.altervista.org/chatlog/"
ftpuser = "jibbolo"
ftppass = "jibbolo"
ftpdir  = "chatlog"

chalogdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), chalogdirname)
if not os.path.isdir(chalogdir):
    os.mkdir(chalogdir)
    

def getfilefromchan(chan):
    anno,mese,giorno,ora,minuti,secondi,nil,nil,nil = time.localtime()
    filename="%s/%s%s%s_%s.log" % (chalogdir,anno,str(mese).rjust(2,"0"),str(giorno).rjust(2,"0"),chan.replace("#",""))
    return filename
    
def writelog(chan,msg):
    filename=getfilefromchan(chan)
    anno,mese,giorno,ora,minuti,secondi,nil,nil,nil = time.localtime()
    open(filename,"a").write("%s:%s.%s - %s\n" % (str(ora).rjust(2,"0"),
                                                          str(minuti).rjust(2,"0"),
                                                          str(secondi).rjust(2,"0"),msg))
                                                          
def chatlogmsg(pyrc,umask,chan,message):
    if chan[0] in logchan.keys() and logchan[chan[0]]:
        writelog(chan[0],"%s: %s" % (umask[0],message[0]))
        
def chatlogjoin(pyrc,umask,chan):
    if chan[0] in logchan.keys() and logchan[chan[0]]:
        writelog(chan[0]," => %s is joined" % umask[0])
        
def chatlogpart(pyrc,umask,chan,message):
    if chan[0] in logchan.keys() and logchan[chan[0]]:
        writelog(chan[0]," <= %s is parted" % umask[0])
        
def chatlogquit(pyrc,umask,message):
    if chan[0] in logchan.keys() and logchan[chan[0]]:
        writelog(chan[0]," <= %s is quitted" % umask[0])
        
        
def chatlogactivate(pyrc,umask,chan,message):
    if chan[0] in logchan.keys():
        action = message[2]
        if action is None:
            if logchan[chan[0]]:
                stato = "ON"
            else:
                stato = "OFF"
            
            filename=getfilefromchan(chan[0])
            pyrc.msg(chan[0],"Chatlog for this channel is %s" % stato)
            if os.path.exists(filename):
                pyrc.msg(chan[0],"Chatlog file %s (%d byte)" % (os.path.basename(filename),os.path.getsize(filename)))
            else:
                pyrc.msg(chan[0],"Chatlog file %s not found!" % os.path.basename(filename))
            
        else:
            if action == "on":
                logchan[chan[0]] = True
                actstr = "Activating"
            else:
                logchan[chan[0]] = False
                actstr = "Deactivating"
                
            pyrc.msg(chan[0],"Chatlog for this chan is now %s" % action.upper())
            writelog(chan[0],"*** %s Chatlog for %s ***" % (actstr,chan[0]))
    else:
        pyrc.msg(chan[0],"Please configure me to use chatlog here")
    
            
def chatlogftp(pyrc,umask,chan,message):
    try:
        f = None
        filename=getfilefromchan(chan[0])
        if not os.path.exists(filename):
            raise Exception('%s not found!' % os.path.basename(filename)) 
        pyrc.msg(chan[0],"Chatlog FTP connecting to %s" % ftphost)
        f = FTP(ftphost,ftpuser,ftppass)
        pyrc.msg(chan[0],"Chatlog FTP connected!")
        f.cwd(ftpdir)
        localfile = open(filename,"rb")
        pyrc.msg(chan[0],"Chatlog FTP sending %s" % os.path.basename(filename))
        f.storbinary('STOR ' + os.path.basename(filename),localfile,1024)
        pyrc.msg(chan[0],"Chatlog FTP done %s" % siteurl+ os.path.basename(filename))
    except Exception, (errstr):
        pyrc.msg(chan[0],"Chatlog FTP error: %s" % errstr)
    except Exception, (errstr):
        pyrc.msg(chan[0],"Chatlog FTP error: %s" % errstr)
    #finally:
    if f:
        f.quit()
        f.close()
                   
events = [
    ['PRIVMSG','(.+)!.+','(#.+)','(.+)',chatlogmsg],
    ['PRIVMSG','(.+)!.+','(#.+)','(!chatlog)( (on|off))?$',chatlogactivate],
    ['PRIVMSG','(.+)!.+','(#.+)','(!chatlog publish)$',chatlogftp],
    ['JOIN' , '(.+)!.+' , '(.+)' , chatlogjoin],
    ['PART' , '(.+)!.+' , '(.+)', '(.+)' , chatlogpart],
    #['QUIT' , '(.+)!.+' , '(.+)' , chatlogquit],
]
